import 'package:flutter/material.dart';

class FloatingScrollbarList2 extends StatefulWidget {
  const FloatingScrollbarList2({super.key});

  @override
  _FloatingScrollbarListState createState() => _FloatingScrollbarListState();
}

class _FloatingScrollbarListState extends State<FloatingScrollbarList2> {
  final ScrollController _scrollController = ScrollController();

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("悬浮滚动条（无setState）")),
      body: Stack(
        children: [
          ListView.builder(
            controller: _scrollController,
            itemCount: 50,
            itemBuilder: (context, index) {
              return ListTile(title: Text("Item $index"));
            },
          ),
          FloatingScrollbar(controller: _scrollController),
        ],
      ),
    );
  }
}

class FloatingScrollbar extends StatelessWidget {
  final ScrollController controller;
  final double scrollbarHeight = 80.0;

  FloatingScrollbar({required this.controller});

  @override
  Widget build(BuildContext context) {
    // double screenHeight = MediaQuery.of(context).size.height;
    // double maxScrollExtent = controller.position.maxScrollExtent;

    return AnimatedBuilder(
      animation: controller,
      builder: (context, child) {
        if (!controller.hasClients ||
            !controller.position.hasContentDimensions) {
          return SizedBox(); // 避免 `position` 尚未计算 `maxScrollExtent`
        }

        double screenHeight = MediaQuery.of(context).size.height;
        double maxScrollExtent =
            controller.position.maxScrollExtent; // 这里已确保不为 null
        double offset = controller.offset;

        double scrollbarPosition =
            (offset / (maxScrollExtent == 0 ? 1 : maxScrollExtent)) *
                (screenHeight - scrollbarHeight - 180);
        //scrollbarPosition.clamp(...) 计算太频繁，影响 UI 性能
        // scrollbarPosition =
        //     scrollbarPosition.clamp(0, screenHeight - scrollbarHeight - 180);

        return Positioned(
          right: 10,
          top: scrollbarPosition + 10, // 避免贴顶
          child: Container(
            height: scrollbarHeight,
            width: 8,
            decoration: BoxDecoration(
              color: Colors.blue.withOpacity(0.7),
              borderRadius: BorderRadius.circular(4),
            ),
          ),
        );
      },
    );
  }
}
